<template>
  <div class="prod-info">
    <!-- 轮播图 -->
    <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
      <van-swipe-item v-for="(item, index) in banner" :key="index">
        <van-image :src="item" width="100vw" />
      </van-swipe-item>
    </van-swipe>
    <van-divider />
    <!-- 商品信息介绍 -->
    <div class="prod-title">
      <van-row>
        <van-col class="prod-title-name" span="18">
          {{ prodData.prodName }}
        </van-col>
        <van-col span="6" class="prod-title-icon">
          <div @click="addOrCancel">
            <van-icon v-if="!isCollection" name="like-o" size="20" />
            <van-icon
              v-if="isCollection"
              style="color: red"
              name="like"
              size="20"
            />
            <span> 收藏</span>
          </div>
        </van-col>
      </van-row>
      <van-row>
        <van-col span="20" class="prod-title-brief">
          {{ prodData.brief }}
        </van-col>
        <van-col span="4" class="prod-title-icon"> </van-col>
      </van-row>
      <van-row>
        <van-col class="prod-title-name prod-title-price" span="20">
          ￥<span class="title-price">{{ prodData.price }}</span>
        </van-col>
        <van-col span="4" class="prod-title-icon"> </van-col>
      </van-row>
    </div>
    <!-- 分割线 -->
    <van-divider :style="{ border: '.5rem solid #ebedf0' }" />
    <!-- 类别 -->
    <div class="prod-categray" v-if="skuList.length > 0" @click="show = true">
      <span class="left">已选 </span> {{ defaultSku.skuName }}
      <span class="right">...</span>
    </div>
    <!-- 分割线 -->
    <van-divider :style="{ border: '.5rem solid #ebedf0', marginBottom: 0 }" />
    <!-- 评价信息 -->
    <van-cell title-style="cell-title" center value="共0条" is-link>
      <!-- 使用 title 插槽来自定义标题 -->
      <template #title>
        <span class="custom-title">评价: </span>
        <span>好评{{ commData.positiveRating }}%</span>
      </template>
    </van-cell>
    <van-grid :column-num="5" :border="false">
      <van-grid-item
        ><van-tag type="warning"
          >全部({{ commData.number }})</van-tag
        ></van-grid-item
      >
      <van-grid-item
        ><van-tag type="warning"
          >好评({{ commData.praiseNumber }})</van-tag
        ></van-grid-item
      >
      <van-grid-item
        ><van-tag type="warning"
          >中评({{ commData.secondaryNumber }})</van-tag
        ></van-grid-item
      >
      <van-grid-item
        ><van-tag type="warning"
          >差评({{ commData.negativeNumber }})</van-tag
        ></van-grid-item
      >
      <van-grid-item
        ><van-tag type="warning"
          >有图({{ commData.picNumber }})</van-tag
        ></van-grid-item
      >
    </van-grid>
    <!-- 内容页 -->
    <div class="content" v-if="prodData.content" v-html="aa"></div>
    <!-- 加入购物车 -->
    <van-action-bar>
      <van-action-bar-icon
        icon="chat-o"
        text="购物车"
        @click="router.push('/shop')"
      />
      <van-action-bar-icon
        icon="shop-o"
        text="店铺"
        @click="router.push('/category')"
      />
      <van-action-bar-button
        type="danger"
        text="立即购买"
        @click="showActive = true"
      />
    </van-action-bar>
    <div style="height: 5rem"></div>

    <!-- 型号面板 -->
    <van-action-sheet
      v-model:show="show"
      title="选择产品类别"
      :close-on-click-overlay="false"
    >
      <div class="action-sheet-content">
        <div v-for="(item, index) in tags" :key="index">
          <div>
            {{ index }}
          </div>
          <van-tag
            type="danger"
            v-for="(i, j) in item"
            :key="j"
            @click="selectTag(index, i)"
            :class="{
              'prop-selected': selectedTag[index] === i ? true : false,
            }"
            plain
            >{{ i }}</van-tag
          >
        </div>
      </div>
      <van-button
        type="danger"
        class="btn"
        :disabled="defaultSku.skuName ? false : true"
        @click="show = false"
        >确定</van-button
      >
    </van-action-sheet>

    <!-- 购物模板 -->
    <van-action-sheet v-model:show="showActive">
      <div class="action-sheet-content">
        <van-card
          :num="comfirm.orderItem.prodCount"
          :price="defaultSku.price ? defaultSku.price : prodData.price"
          :desc="prodData.brief"
          :title="defaultSku.skuName ? defaultSku.skuName : prodData.prodName"
          :thumb="defaultSku.pic ? defaultSku.pic : prodData.pic"
        >
          <template #footer>
            <van-stepper v-model="comfirm.orderItem.prodCount" />
          </template>
        </van-card>

        <div style="height: 1rem"></div>
        <div v-for="(item, index) in tags" :key="index">
          <div>
            {{ index }}
          </div>
          <van-tag
            type="danger"
            v-for="(i, j) in item"
            :key="j"
            @click="selectTag(index, i)"
            :class="{
              'prop-selected': selectedTag[index] === i ? true : false,
            }"
            plain
            >{{ i }}</van-tag
          >
        </div>

        <div style="height: 1rem"></div>
        <div class="shopcart-button">
          <van-button class="left" @click="shopCarAdd">加入购物车</van-button>
          <van-button class="right" type="danger" @click="buyNow"
            >立即购买</van-button
          >
        </div>
      </div>
    </van-action-sheet>
  </div>
</template>

<script setup>
import { formatHtml } from "@/utils/utils.js";
import { ref, reactive, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  prodMain,
  isCollection1,
  addOrCancel1,
  prodCommData,
  changeItem,
} from "@/api/prodinfo.js";
const route = useRoute();
const router = useRouter();
const ids = ref();
ids.value = route.query.ids;
const banner = ref([]);
const show = ref(false);
const showActive = ref(false);
const skuList = ref([]);
const prodData = ref({});
const isCollection = ref(false);
const commData = reactive({
  positiveRating: 0,
  number: 0,
  praiseNumber: 0,
  secondaryNumber: 0,
  negativeNumber: 0,
  picNumber: 0,
});
const shopCar = reactive({
  basketId: 0,
  prodId: 0,
  skuId: 0,
  shopId: 0,
  count: 0,
  distributionCardNo: "",
});
const comfirm = reactive({
  basketIds: [],
  orderItem: {
    prodId: 0,
    skuId: 0,
    prodCount: 1,
    shopId: 0,
    distributionCardNo: "",
  },
  addrId: 0,
  userChangeCoupon: 0,
  couponIds: [],
});
const selectedTag = ref({});
const defaultSku = ref({});
const tags = ref({});
onMounted(() => {
  init();
});
const aa = ref();
// 初始化方法
async function init() {
  let result = await prodMain({
    prodId: ids.value,
  });
  // console.log(result, "result");
  banner.value = result.imgs.split(",");
  prodData.value = result;
  skuList.value = result.skuList;
  aa.value = formatHtml(prodData.value.content);
  // console.log(formatHtml(prodData.value.content), "prodData.value");
  isCollection.value = await isCollection1({ prodId: result.prodId });
  commData.value = await prodCommData({ prodId: result.prodId });
  loadData(skuList.value);
}
// 处理型号模块方法
function loadData(sku) {
  // console.log(sku, "sku");
  const properties = [];
  let properObject = {};
  let defaultArr = [];
  for (let i = 0; i < sku.length; i++) {
    properties.push(sku[i].properties);
  }
  // console.log(properties, "properties");
  // 处理属性
  for (let i = 0; i < properties.length; i++) {
    const propStr = properties[i];
    const propArr = propStr.split(";");
    if (defaultArr.length === 0) {
      defaultArr = propArr;
      defaultSku.value = sku[i];
      // console.log(defaultSku.value, "defaultSku.value");
      if (sku.length == 1) return;
    }
    console.log(propArr, "Arr");
    for (var j = 0; j < propArr.length; j++) {
      const valueStr = propArr[j];
      const valueArr = valueStr.split(":");
      console.log(valueArr[1], "valueArr");
      // 处理每一项属性
      if (!properObject[valueArr[0]]) {
        properObject[valueArr[0]] = new Set();
      }
      // console.log(properObject, "properObject");
      properObject[valueArr[0]].add(valueArr[1]);
    }
  }
  tags.value = properObject;
  console.log(tags, "tags");
  for (let i = defaultArr.length - 1; i >= 0; i--) {
    const newStr = defaultArr[i];
    const newArr = newStr.split(":");
    selectedTag.value[newArr[0]] = newArr[1];
  }
}
// 选择标签
function selectTag(propTitle, propValue) {
  selectedTag.value[propTitle] = propValue;
  let str = "";
  for (let item in selectedTag.value) {
    str = item + ":" + selectedTag.value[item] + ";" + str;
  }
  str = str.substring(0, str.length - 1);
  for (let i = 0; i < skuList.value.length; i++) {
    if (skuList.value[i].properties === str) {
      defaultSku.value = skuList.value[i];
      return;
    }
  }
}
// 收藏方法
async function addOrCancel() {
  await addOrCancel1(prodData.value.prodId);
  isCollection.value = await isCollection1({ prodId: prodData.value.prodId });
}
// 添加购物车
function shopCarAdd() {
  shopCar.prodId = prodData.value.prodId;
  shopCar.shopId = prodData.value.shopId;
  shopCar.skuId = defaultSku.value.skuId;
  shopCar.count = comfirm.orderItem.prodCount;

  changeItem(shopCar)
    .then((res) => {
      console.log(res, "111111111");

      if (res.code === "A00001") {
        showToast({
          message: "添加失败",
          icon: "cross",
        });
      } else {
        showToast({
          message: "添加成功",
          icon: "success",
        });
      }

      showActive.value = false;
    })
    .catch((err) => {
      console.log(err, "失败");
    });
}
// 结单
function buyNow() {
  comfirm.orderItem.prodId = prodData.value.prodId;
  comfirm.orderItem.shopId = prodData.value.shopId;
  // console.log(defaultSku.value);
  comfirm.orderItem.skuId = defaultSku.value.skuId;
  sessionStorage.setItem("confirm", JSON.stringify(comfirm));
  router.push("/order");
}
</script>
<style lang="scss" scoped>
.shopcart-button {
  .left {
    width: 50%;
    color: #fff;
    background-color: #595959;
    border: 1px solid #595959;
  }

  .right {
    width: 50%;
  }
}

.prop-selected {
  color: #fff !important;
  background-color: red !important;
}

.prod-info ::v-deep .van-tag {
  color: #ee0a24;
  margin-left: 1rem;
  padding: 0.3rem;
}

.prod-info ::v-deep .action-sheet-content {
  padding: 1rem;
}

.prod-info ::v-deep .van-card {
  background-color: #fff;
}

.van-tag--warning {
  background-color: #ff976a;
  padding: 0.3rem;
}

.prod-info {
  padding: auto;

  .van-cell {
    .van-cell__title {
      text-align: left;
    }
  }

  .content {
    padding: 0%;
  }

  .prod-categray {
    height: 1rem;
    line-height: 1rem;
    text-align: left;
    padding-left: 1rem;
    font-weight: 700;

    .left {
      font-size: 0.9rem;
      color: grey;
      font-weight: 200;
    }

    .right {
      text-align: right;
      float: right;
      margin-right: 1rem;
      font-weight: 200;
    }
  }

  .prod-title {
    .prod-title-brief {
      height: 3rem;
      padding-left: 1rem;
      text-align: left;
      font-size: 0.6rem;
      color: #595959;
    }

    .prod-title-price {
      color: red;

      .title-price {
        font-size: 1.5rem;
        font-weight: 500;
      }
    }

    .prod-title-name {
      height: 3rem;
      padding-left: 1rem;
      text-align: left;
    }

    .prod-title-icon {
      height: 3rem;
      line-height: 3rem;
      padding-right: 1rem;
    }
  }
}
.btn {
  width: 80%;
  // margin-top:20px;
  margin-left: 35px;
}
</style>
